package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.BaseContext;
import com.example.entity.AddressBook;
import com.example.mapper.AddressBookMapper;
import com.example.service.IAddressBookService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 地址管理 服务实现类
 * </p>
 *
 * @author czx
 * @since 2022-04-28
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    /**
     * 根据用户id获取地址列表信息
     *
     * @param userId 用户id
     * @return 地址列表
     */
    @Override
    public List<AddressBook> listByUserId(Long userId) {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(null != userId, AddressBook::getUserId, userId);
        // 默认地址排在最前面，接着是按更新时间来排
        wrapper.orderByDesc(AddressBook::getIsDefault).orderByDesc(AddressBook::getUpdateTime);
        return this.list(wrapper);
    }

    /**
     * 根据地址id修改默认地址
     *
     * @param addressBook 地址
     * @return 修改结果
     */
    @Override
    public boolean updateByIsDefault(AddressBook addressBook) {
        //更新条件构造器
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        wrapper.set(AddressBook::getIsDefault, 0);
        //不是默认地址就可以删除
        wrapper.set(AddressBook::getIsDeleted,1);
        this.update(wrapper);
        addressBook.setIsDefault(1);
        //修改成为不能删除
        addressBook.setIsDeleted(0);
        return this.updateById(addressBook);
    }

    /**
     * 删除地址信息
     *
     * @param ids 地址id
     * @return 删除结果
     */
    @Override
    public boolean removeBatchByIdsAndIsDeleted(List<Long> ids) {
        List<AddressBook> addressBookList = this.listByIds(ids);
        // 判断地址是否能删除
        for (AddressBook addressBook : addressBookList) {
            if(addressBook.getIsDeleted()==0){
                return false;
            }
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 根据用户id获取用户默认地址
     *
     * @param currentId 用户id
     * @return 默认地址信息
     */
    @Override
    public AddressBook getByIsDefault(Long currentId) {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId,currentId);
        wrapper.eq(AddressBook::getIsDefault,1);
        return this.getOne(wrapper);
    }
}
